<template>
  <div ref="contentRef" class="content">
    {{ text }}
  </div>
  <el-tooltip :content="text" placement="top" :disabled="!isOverflow">
    <div ref="tooltipRef" class="tooltip-trigger" />
  </el-tooltip>
</template>

<script>
import { ref, onMounted, onUnmounted, watch } from "vue";

export default {
  name: "EllipsisTooltip",
  props: {
    text: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const contentRef = ref(null);
    const tooltipRef = ref(null);
    const isOverflow = ref(false);

    const checkOverflow = () => {
      if (contentRef.value && tooltipRef.value) {
        isOverflow.value =
          contentRef.value.scrollWidth > contentRef.value.clientWidth;
        tooltipRef.value.style.display = isOverflow.value
          ? "inline-block"
          : "none";
      }
    };

    const handleResize = () => {
      checkOverflow();
    };

    onMounted(() => {
      window.addEventListener("resize", handleResize);
      checkOverflow();
    });

    onUnmounted(() => {
      window.removeEventListener("resize", handleResize);
    });

    watch(
      () => props.text,
      () => {
        checkOverflow();
      }
    );

    return {
      contentRef,
      tooltipRef,
      isOverflow
    };
  }
};
</script>

<style scoped>
.content {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tooltip-trigger {
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  width: 100%;
  height: 100%;
}
</style>
